<template>
	<u-upload :ref="'upload'+index" :width="width" :height="height" :file-list="fileList" :action="action" :header="header" :form-data="formData" :max-count="maxCount" :max-size="maxSize" :upload-text="uploadText" @on-oversize="oversize" @on-success="success" @on-remove="remove" :show-tips="false"></u-upload>
</template>

<script>
	export default {
		name: 'ImageUpload',
		props: {
			value: [String, Object, Array],
			index: {
				type: [String, Number],
				default: 0
			},
			formData: {
				type: Object,
				default: ()=>{}
			},
			maxSize: {
				type: [String, Number],
				default: 50*1024*1024
			},
			maxCount: {
				type: [String, Number],
				default: 9
			},
			width: {
				type: [String, Number],
				default: 200
			},
			height: {
				type: [String, Number],
				default: 200
			},
			uploadText: {
				type: String,
				default: '选择图片'
			},
		},
		data() {
			return {
				action:this.baseUrl+'/common/upload',
				header:{
					Authorization: uni.getStorageSync('token'),
				},
				fileList:[]
			}
		},
		watch:{
			value(val){
				if (val) this.fileList = JSON.parse(val);
			}
		},
		created() {
			if (this.value) this.fileList = JSON.parse(this.value);
		},
		methods: {
			oversize(file, lists, name){
				this.$u.toast('选择的图片大于'+parseInt(this.maxSize/1024/1024)+'M，请重新上传！')
			},
			success(data, index, lists, name){
				if(data.code === 200){
					let imgs = JSON.stringify(lists.map(row=>{
						return { name: row.response.name, url: row.response.url }
					}))
					this.$emit("input", imgs)
					this.$emit('change',imgs)
				}else{
					lists.forEach((row,index)=>{
						if(!row.response.url){
							this.$refs['upload'+this.index].remove(index)
						}
					})
					if(data.code === 401){
						uni.removeStorageSync('token')
						uni.removeStorageSync('userInfo')
						uni.navigateTo({
							url:'/pages/login'
						})
					}else{
						uni.showToast({title:data.msg,icon:'none'})
					}
				}
			},
			remove(index, lists, name){
				let imgs = lists.length?JSON.stringify(lists.map(row=>{
					return { name: row.response.name, url: row.response.url }
				})):''
				this.$emit("input", imgs)
				this.$emit('change',imgs)
			}
		}
	}
</script>
